package com.api.Controller;

import com.common.redis.service.RedisService;
import com.comon.core.utils.ImageUtil;
import com.comon.core.utils.PasswordUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created with Intellij IDEA.
 * Description;
 * User:TQ02
 * Data:2024-08-28
 * Time:9:08
 * Text：
 */
@RestController
public class ServiceController {

    @Autowired
    private ImageUtil imageUtil;
    @Autowired
    private PasswordUtil passwordUtil;


    @RequestMapping("/generateImage")
    public void generateImage(HttpServletRequest req, HttpServletResponse res){
        imageUtil.init();
        //验证码文字
        final String verifyCode=imageUtil.getStr();
        //验证码图片
        final ByteArrayInputStream image=imageUtil.getImage();
        res.setContentType("image/jpeg");
        //将验证码存储在session当中
        HttpSession session= req.getSession();
        String secret = passwordUtil.encrypt(verifyCode);
        session.setAttribute("verifyCode",secret);
        System.out.println(session.getId()+" "+secret);
        byte[] bytes=new byte[1024];
        try(final ServletOutputStream out=res.getOutputStream()){
            while(image.read(bytes)!=-1){
                out.write(bytes);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
